import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Button,
  Table,
  Space,
  Typography,
  Row,
  Col,
  Statistic,
  Tag,
  Avatar,
  Input,
  Select,
  Modal,
  message,
  Popconfirm,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  UserOutlined,
  TeamOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
  CrownOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { teamApi } from '../services/api';

const { Title, Text } = Typography;
const { Option } = Select;

interface Team {
  teamId: string;
  name: string;
  description?: string;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
  stats?: {
    memberCount: number;
    telemetryPointCount: number;
    extractionCount: number;
  };
  userRole?: string;
  permissions?: {
    canView: boolean;
    canEdit: boolean;
    canManageMembers: boolean;
    canDelete: boolean;
    canManageAnalysis: boolean;
  };
}

const TeamList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [teams, setTeams] = useState<Team[]>([]);
  const [filteredTeams, setFilteredTeams] = useState<Team[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [roleFilter, setRoleFilter] = useState<string>('all');
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deletingTeam, setDeletingTeam] = useState<Team | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });

  // 防止重复API调用的ref
  const isLoadingRef = useRef(false);

  // 加载团队列表
  const loadTeams = async () => {
    if (isLoadingRef.current) {
      console.log('📋 [TeamList] Teams API已在加载中，跳过重复请求');
      return;
    }

    try {
      isLoadingRef.current = true;
      setLoading(true);
      const response = await teamApi.getTeams();
      if (response && Array.isArray(response)) {
        // Transform API response to match Team interface
        const transformedTeams: Team[] = response.map((team: any) => ({
          teamId: team.id,
          name: team.name,
          description: team.description,
          createdBy: team.created_by,
          createdAt: team.created_at,
          updatedAt: team.updated_at,
          stats: {
            memberCount: team.member_count,
            telemetryPointCount: 0, // TODO: Get from API
            extractionCount: 0, // TODO: Get from API
          }
        }));
        setTeams(transformedTeams);
      }
    } catch (error: any) {
      console.error('Failed to load teams:', error);
      message.error('加载团队列表失败');
    } finally {
      setLoading(false);
      isLoadingRef.current = false;
    }
  };

  useEffect(() => {
    loadTeams();
  }, []);

  // 搜索和过滤
  useEffect(() => {
    let filtered = teams;

    // 名称搜索
    if (searchTerm) {
      filtered = filtered.filter(team =>
        team.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        team.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 角色过滤
    if (roleFilter !== 'all') {
      filtered = filtered.filter(team => team.userRole === roleFilter);
    }

    setFilteredTeams(filtered);
    // 重置到第1页当搜索或过滤条件改变时
    setPagination(prev => ({ ...prev, current: 1 }));
  }, [teams, searchTerm, roleFilter]);

  // 删除团队
  const handleDeleteTeam = async () => {
    if (!deletingTeam) return;

    try {
      await teamApi.deleteTeam(deletingTeam.teamId);
      message.success('团队删除成功');
      setDeleteModalVisible(false);
      setDeletingTeam(null);
      loadTeams();
    } catch (error: any) {
      console.error('Failed to delete team:', error);
      message.error(error.response?.data?.error?.message || '删除团队失败');
    }
  };

  // 获取角色标签
  const getRoleTag = (role: string) => {
    const roleConfig = {
      PL: { color: 'gold', icon: <CrownOutlined />, text: 'PL' },
      SE: { color: 'blue', icon: <SettingOutlined />, text: 'SE' },
      MDE: { color: 'green', icon: <UserOutlined />, text: 'MDE' },
      ADMIN: { color: 'purple', icon: <SettingOutlined />, text: '管理员' },
      MEMBER: { color: 'default', icon: <UserOutlined />, text: '成员' },
    };

    const config = roleConfig[role as keyof typeof roleConfig];
    if (!config) {
      return <Tag color="default">{role || '未知'}</Tag>;
    }

    return (
      <Tag color={config.color} icon={config.icon}>
        {config.text}
      </Tag>
    );
  };

  // 表格列定义
  const columns: ColumnsType<Team> = [
    {
      title: '团队名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Avatar icon={<TeamOutlined />} size="small" />
          <div>
            <div style={{ fontWeight: 600 }}>{text}</div>
            {record.description && (
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {record.description}
              </Text>
            )}
          </div>
        </Space>
      ),
    },
    {
      title: '我的角色',
      dataIndex: 'userRole',
      key: 'userRole',
      width: 120,
      render: (role) => getRoleTag(role || ''),
    },
    {
      title: '成员数量',
      key: 'memberCount',
      width: 100,
      render: (_, record) => (
        <Space>
          <UserOutlined />
          <Text>{record.stats?.memberCount || 0}</Text>
        </Space>
      ),
    },
    {
      title: '遥测点',
      key: 'telemetryPointCount',
      width: 100,
      render: (_, record) => (
        <Text>{record.stats?.telemetryPointCount || 0}</Text>
      ),
    },
    {
      title: '提取任务',
      key: 'extractionCount',
      width: 100,
      render: (_, record) => (
        <Text>{record.stats?.extractionCount || 0}</Text>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (text) => new Date(text).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            size="small"
            type="primary"
            onClick={() => navigate(`/teams/${record.teamId}`)}
          >
            查看
          </Button>
          {record.permissions?.canEdit && (
            <Button
              size="small"
              icon={<EditOutlined />}
              onClick={() => navigate(`/teams/${record.teamId}/settings`)}
            >
              设置
            </Button>
          )}
          {record.permissions?.canDelete && (
            <Popconfirm
              title="删除团队"
              description="确定要删除这个团队吗？此操作不可恢复。"
              onConfirm={() => {
                setDeletingTeam(record);
                setDeleteModalVisible(true);
              }}
              okText="确定"
              cancelText="取消"
              okType="danger"
            >
              <Button
                size="small"
                danger
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  // 统计数据
  const stats = {
    total: teams.length,
    pl: teams.filter(t => t.userRole === 'PL').length,
    se: teams.filter(t => t.userRole === 'SE').length,
    mde: teams.filter(t => t.userRole === 'MDE').length,
    admin: teams.filter(t => t.userRole === 'ADMIN').length,
    member: teams.filter(t => t.userRole === 'MEMBER').length,
  };

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
      {/* 页面标题和操作 */}
      <Row justify="space-between" align="middle" style={{ marginBottom: '24px' }}>
        <Col>
          <Title level={2} style={{ margin: 0 }}>
            我的团队
          </Title>
          <Text type="secondary">
            管理您参与的团队和协作项目
          </Text>
        </Col>
        <Col>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/teams/create')}
          >
            创建团队
          </Button>
        </Col>
      </Row>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <TeamOutlined style={{ marginRight: 8, color: '#1890ff' }} />
              <Statistic
                title="总团队数"
                value={stats.total}
                valueStyle={{ color: '#1890ff' }}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <CrownOutlined style={{ marginRight: 8, color: '#faad14' }} />
              <Statistic
                title="PL身份"
                value={stats.pl}
                valueStyle={{ color: '#faad14' }}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <SettingOutlined style={{ marginRight: 8, color: '#1890ff' }} />
              <Statistic
                title="SE身份"
                value={stats.se}
                valueStyle={{ color: '#1890ff' }}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <UserOutlined style={{ marginRight: 8, color: '#52c41a' }} />
              <Statistic
                title="MDE身份"
                value={stats.mde}
                valueStyle={{ color: '#52c41a' }}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 筛选控件 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16}>
          <Col span={12}>
            <Input.Search
              placeholder="搜索团队名称或描述"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onSearch={setSearchTerm}
            />
          </Col>
          <Col span={6}>
            <Select
              style={{ width: '100%' }}
              value={roleFilter}
              onChange={setRoleFilter}
              placeholder="筛选角色"
            >
              <Option value="all">全部角色</Option>
              <Option value="PL">PL</Option>
              <Option value="SE">SE</Option>
              <Option value="MDE">MDE</Option>
              <Option value="ADMIN">管理员</Option>
              <Option value="MEMBER">成员</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Text type="secondary">
              共 {filteredTeams.length} 个团队
            </Text>
          </Col>
        </Row>
      </Card>

      {/* 团队列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredTeams}
          rowKey="teamId"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: filteredTeams.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination({
                current: page,
                pageSize: pageSize || 10,
              });
            },
            onShowSizeChange: (current, size) => {
              setPagination({
                current: 1,
                pageSize: size,
              });
            },
          }}
        />
      </Card>

      {/* 删除确认对话框 */}
      <Modal
        title={
          <Space>
            <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />
            删除团队确认
          </Space>
        }
        open={deleteModalVisible}
        onOk={handleDeleteTeam}
        onCancel={() => {
          setDeleteModalVisible(false);
          setDeletingTeam(null);
        }}
        okText="确定删除"
        cancelText="取消"
        okType="danger"
      >
        <div style={{ marginBottom: '16px' }}>
          <Text strong>团队名称：{deletingTeam?.name}</Text>
        </div>
        <Text type="secondary">
          您确定要删除这个团队吗？此操作将同时删除：
        </Text>
        <ul style={{ marginTop: '8px', color: '#666' }}>
          <li>所有团队成员关系</li>
          <li>团队相关的提取任务</li>
          <li>团队分析数据</li>
        </ul>
        <Text type="danger" strong>
          此操作不可恢复，请谨慎操作！
        </Text>
      </Modal>
    </div>
  );
};

export default TeamList;